<template>
  <div class="app-container">
    <div class="bgWhite radius8  flex col-center row-between pr20">
      <el-form class="p20" :model="queryParams" ref="queryRef" :inline="true"
        v-show="showSearch">
        <el-form-item label="部门名称" prop="keyword">
          <el-input v-model="queryParams.keyword" placeholder="请输入部门名称" clearable class="resetInput"
            style="width: 200px" :suffix-icon="Search" @keyup.enter="handleQuery" />
        </el-form-item>
        
      </el-form>
	  <div>
		<el-button class="searchBtn" type="defaultBtn" @click="handleQuery">查询</el-button>
		<el-button class="searchBtn" icon="Refresh" @click="resetQuery">重置</el-button>
	  </div>
    </div>

    <div class="bgWhite radius8 p20 mt25">
      <div class="flex col-center row-between mb20">
        <span class="fb fs16">线上部门、小组商机分配规则</span>
        <div>
          <el-button type="defaultBtn" @click="handleAdd" v-hasPermi="['opportunity_rules:edit']">批量修改分配规则
          </el-button>
          <el-button type="info" icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
        </div>
      </div>

      <el-table v-if="refreshTable" v-loading="loading" :data="rulesList" row-key="deptId"
        :cell-style="{ height: '54px' }" :default-expand-all="isExpandAll"
        :header-row-style="{ background: '#FAFAFA', color: '#0C1019', height: '54px' }"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="deptId" v-if="false" />

        <el-table-column label="部门名称" align="center" prop="deptName" />
        <el-table-column label="成员数量" align="center" prop="usersNumber" />
        <el-table-column label="主管人员" align="center" prop="leader" />
        <el-table-column label="商机分配规则" align="center" prop="executionType">
          <template v-slot="scope">
            <dict-tag :options="bus_opportuity_rules_type" :value="scope.row.executionType" />
          </template>
        </el-table-column>

        <el-table-column label="更新时间" align="center" prop="updateTime">
          <template #default="scope">
            <p v-if="scope.row.updateTime">{{ scope.row.updateTime }}</p>
            <p v-else>{{ scope.row.createTime }} </p>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link class="linkBtnColor" type="primary" @click="handleUpdate(scope.row)"
			v-hasPermi="['opportunity:edit']"
			>修改分配规则
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 添加或修改物流规则对话框 -->
    <el-dialog :title="title" center v-model="open" width="450px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择部门" prop="ids">
          <el-select :disabled="selectDisabled" v-model="selectValue" placeholder="请选择" size="large"
            clearable multiple>
            <template #label="{ label, value }">
              <span>{{ label }}: </span>
              <span style="font-weight: bold">{{ value }}</span>
            </template>
            <el-option v-for="item in selectDept" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="分配规则" prop="executionType">
          <el-radio-group v-model="radioValue">
            <el-radio class="bus-radio-button-selected-bg-color" v-for="item in bus_opportuity_rules_type"
              :label="item.value" :value="item.value">{{
                item.label
              }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer text-right mt30">
		  <el-button class="cancelSubBtn" @click="cancel">取 消</el-button>
		  <el-button type="primary" @click="submitForm" class="mainSubBtn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="OpportunityGroupRulesSetup">
import { listRules, addRules } from "@/api/business/rules_opportunity";

const { proxy } = getCurrentInstance();
const {
  bus_opportuity_rules_type
} = proxy.useDict(
  "bus_opportuity_rules_type"
);

//默认单选参数
const radioValue = ref();

//默认下拉
var selectDept = [];
const selectValue = ref([]);
const selectDisabled = ref(false);

//折叠
const isExpandAll = ref(true);
//刷新表单
const refreshTable = ref(true);
// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 规则表格数据
const rulesList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: null,
});
// 表单参数
const form = ref({});
// 表单校验
const rules = ref({
  ids: [
    { required: true, message: "选择部门不能为空", trigger: "blur" },
  ],
  executionType: [
    { required: true, message: "分配规则不能为空", trigger: "blur" },
  ],
});

/** 查询规则列表 */
function getList() {
  loading.value = true;
  listRules(queryParams.value).then((response) => {
    rulesList.value = proxy.handleTree(response.data, "deptId");
    total.value = response.total;
    loading.value = false;
  });
}

function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    ids: null,
    executionType: null,
  }
  proxy.resetForm("form");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

const selectJson = ref([]);

//构建多选部门id
function buildDeptIds() {
  selectDept = [];
  selectValue.value = [];
  selectDisabled.value = false;

  radioValue.value = "1001";
  selectJson.value.map(item => {
    const id = item.value
    const name = item.label;

    selectDept.push({ value: id, label: name });
    selectValue.value.push(id);
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectJson.value = [];
  selection.map(item => {
    selectJson.value.push({ value: item.deptId, label: item.deptName });
  });
  buildDeptIds();
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 表 修改分配规则 操作 */
function handleAdd() {
	if(multiple.value == true){
		 proxy.$modal.msgError("请选择部门");
		return false
	}
  buildDeptIds();
  reset();
  open.value = true;
  title.value = "修改分配规则";
}

/** 行 修改分配规则 */
function handleUpdate(row) {
  selectValue.value = [row.deptId];
  selectDisabled.value = true;
  selectDept = [{ value: row.deptId, label: row.deptName }];
  radioValue.value = row.executionType;

  reset();
  open.value = true;
  title.value = "修改分配规则";
}

/** 提交按钮 */
function submitForm() {
  form.value.ids = selectValue.value;
  form.value.executionType = radioValue.value;

  proxy.$refs["form"].validate((valid) => {
    if (valid) {
      addRules(form.value).then((response) => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      });
    }
  })
}

getList();
watch(() => bus_opportuity_rules_type.value, arr => radioValue.value = arr[0].value)
</script>
